let CRC = require("../../utils/CRC")
let app = getApp()
// pages/device_setup/index.js
const plugin = requirePlugin('quecPlugin')
Page({
  data: { 
    dropIcon:"../../images/selector.png",
    getBackIcon:"../../images/backtrack_icon.png",
    frequencyId : 13,
    frequencyUpload: 0,
    frequencyUploaded: false,
    frequencySource: [//主频率源
      '功能码设定，掉电记忆', //0
      '面板电位器', //1
      'AI1', //2
      'AI2', //3
      '多段指令', //4
      'PLC', //5
      '恒压供水', //6
      '通用 PID', //7
      '通讯设定', //8
      '保留' //9
    ],
    commandId : 14,
    commandUpload: 0,
    commandUploaded: false,
    commandSource: [//命令源
      '面板控制', //0
      '端子控制', //1
      '通讯控制', //2
    ],
    decelerationTimeId:15,
    decelerationTimeJudge: false,
    decelerationTimeUploaded: false,
    decelerationTimeDisplay:'',
    decelerationTimeUpload:'',
    accelerationTimeId:16,
    accelerationTimeJudge: false,
    accelerationUploaded: false,
    accelerationTimeDisplay:'',
    accelerationTimeUpload:'',
    maxFrequencyId:17,
    maxFrequencyJudge: false,
    maxFrequencyUploaded: false,
    maxFrequencyDisplay:'',
    maxFrequencyUpload:'',
    restoreFactoryId:'18',
    restoreFactoryUpload:'1',
    di1Id:19,
    di1Upload:0, 
    di1Uploaded: false,
    di1Source: [//DI1端子功能选择
      '无功能', //0
      '正转运行 FWD', //1
      '反转运行 REV', //2
      '三线式运行控制', //3
      '两线式/三线式切换', //4
      '正向点动', //5
      '反向点动', //6
      '故障复位', //7
      '多段指令端子 1', //8
      '多段指令端子 2', //9
      '多段指令端子 3', //10
      '外部停车端子', //11
      '自由停车', //12
      '外部端子停机', //13
      '紧急停车', //14
      '直流制动', //15
      '减速直流制动', //16
      '外部故障输入(常开)', //17
      '外部故障常闭输入', //18
      '运行命令切换端子 1', //19
      '命令源切换端子 2', //20
      '端子 UP', //21
      '端子 DOWN', //22
      'UP/DOWN 设定清零', //23
      '频率源切换', //24
      '主频率源与预置频率切换', //25
      '辅频率源与预置频率切换', //26
      '频率设定有效端子', //27
      '加减速禁止', //28
      '加减速时间选择端子 1', //29
      'PLC 状态复位', //30
      '速度控制/转矩控制切换', //31
      '保留', //32
      '保留', //33
      '第二压力设定', //34
      '运行暂停', //35
    ],
    di2Id:20,
    di2Upload:0, 
    di2Uploaded: false,
    di2Source: [//DI2端子功能选择
      '无功能', //0
      '正转运行 FWD', //1
      '反转运行 REV', //2
      '三线式运行控制', //3
      '两线式/三线式切换', //4
      '正向点动', //5
      '反向点动', //6
      '故障复位', //7
      '多段指令端子 1', //8
      '多段指令端子 2', //9
      '多段指令端子 3', //10
      '外部停车端子', //11
      '自由停车', //12
      '外部端子停机', //13
      '紧急停车', //14
      '直流制动', //15
      '减速直流制动', //16
      '外部故障输入(常开)', //17
      '外部故障常闭输入', //18
      '运行命令切换端子 1', //19
      '命令源切换端子 2', //20
      '端子 UP', //21
      '端子 DOWN', //22
      'UP/DOWN 设定清零', //23
      '频率源切换', //24
      '主频率源与预置频率切换', //25
      '辅频率源与预置频率切换', //26
      '频率设定有效端子', //27
      '加减速禁止', //28
      '加减速时间选择端子 1', //29
      'PLC 状态复位', //30
      '速度控制/转矩控制切换', //31
      '保留', //32
      '保留', //33
      '第二压力设定', //34
      '运行暂停', //35
    ],
    scheduledRunningTimeId:21,
    scheduledRunningTimeJudge: false,
    scheduledRunningTimeUploaded: false,
    scheduledRunningTimeDisplay:'',
    scheduledRunningTimeUpload:'',
    userPasswordId:22,
    userPasswordJudge: false,
    userPasswordUploaded: false,
    userPasswordDisplay:'',
    userPasswordUpload:'',
    accumulatedPpowerOnTimeId:23,
    accumulatedPpowerOnTimeJudge: false,
    accumulatedPpowerOnTimeUploaded: false,
    accumulatedPpowerOnTimeDisplay:'',
    accumulatedPpowerOnTimeUpload:'',
    PMSMbackEMFId:24,
    PMSMbackEMFJudge: false,
    PMSMbackEMFUploaded: false,
    PMSMbackEMFDisplay:'',
    PMSMbackEMFUpload:'',
    motorParameterSelfTestId:25,
    motorParameterSelfTestUpload:0, 
    motorParameterSelfTestUploaded: false,
    motorParameterSelfTestSource: [//电机参数自检测
      '无操作', //0
      '静止参数辨识', //1
      '动态参数辨识', //2
    ],
    motorControlMethodId:26,
    motorControlMethodUpload:0, 
    motorControlMethodUploaded: false,
    motorControlMethodSource: [//电机控制方式
      'V/F 控制', //0
      '异步电机无速度传感器矢量控制（IMSVC）', //1
      '同步电机无速度传感器矢量控制（FMSVC）', //2
    ],
    ratedPowerId:27,
    ratedPowerJudge: false,
    ratedPowerUploaded: false,
    ratedPowerDisplay:'',
    ratedPowerUpload:'',
    ratedVoltageId:28,
    ratedVoltageJudge: false,
    ratedVoltageUploaded: false,
    ratedVoltageDisplay:'',
    ratedVoltageUpload:'',
    ratedCurrentId:29,
    ratedCurrentJudge: false,
    ratedCurrentUploaded: false,
    ratedCurrentDisplay:'',
    ratedCurrentUpload:'',
    ratedSpeedId:30,
    ratedSpeedJudge: false,
    ratedSpeedUploaded: false,
    ratedSpeedDisplay:'',
    ratedSpeedUpload:'',
    ratedFrequencyId:31,
    ratedFrequencyJudge: false,
    ratedFrequencyUploaded: false,
    ratedFrequencyDisplay:'',
    ratedFrequencyUpload:'',
    torqueSetValueId:32,
    torqueSetValueJudge: false,
    torqueSetValueUploaded: false,
    torqueSetValueDisplay:'',
    torqueSetValueUpload:'',
    torqueSettingId:33,
    torqueSettingUpload:0, 
    torqueSettingUploaded: false,
    torqueSettingSource: [//转矩设定源
      '参数设定（F8-10）', //0
      '面板电位器设定', //1
      'AI1', //2
      'AI2', //3
      '通讯给定', //4
      '两者中的最小值（AI1,AI2）', //5
      '两者中的最大值（AI1,AI2）', //6
      '保留', //7
    ],
    speedTorqueControlId:34,
    speedTorqueControlUpload:0, 
    speedTorqueControlUploaded: false,
    speedTorqueControlSource: [//速度转矩控制
      '速度控制', //0
      '转矩控制', //1
    ],
    highSpeedVelocityGainId:35,
    highSpeedVelocityGainJudge: false,
    highSpeedVelocityGainUploaded: false,
    highSpeedVelocityGainDisplay:'',
    highSpeedVelocityGainUpload:'',
    MKIId:36,
    MKIJudge: false,
    MKIUploaded: false,
    MKIDisplay:'',
    MKIUpload:'',
    MKPId:37,
    MKPJudge: false,
    MKPUploaded: false,
    MKPDisplay:'',
    MKPUpload:'',
    destinationStationAddress:'01',
    functionCode:{
      "ReadHoldingRegister":"03",
      "PresetSingleRegister":"06"
    },
    modBusIdtoAdd:{
      13:"F001",
      14:"F000",
      15:"F005",
      16:"F004",
      17:"F009",
      19:"F100",
      20:"F101",
      21:"F605",
      23:"F604",
      24:"F805",
      25:"F807",
      26:"F806",
      27:"F800",
      28:"F801",
      29:"F802",
      30:"F804",
      31:"F803",
      32:"F80A",
      33:"F809",
      34:"F808",
      35:"F901",
      36:"F90E",
      37:"F90D"
    },
    readParameterID:0//电机相关参数查询所需ID
  },
  /**
   * 生命周期函数--监听页面加载
   */
  
  onLoad(options) {
    let that = this;
    getApp().watch(that.watchBack)
    console.log("device_setup已加载");
    app.globalData.pageID = "2"
    console.log("当前页面标识pageID：" + app.globalData.pageID)
    if (options.item) {
      let dItem = JSON.parse(decodeURIComponent(options.item))
      this.setData({
        pk: dItem.productKey,
        dk: dItem.deviceKey,
        curDevice: dItem
      })
    }
  },

  watchBack(readParameterVal){
    const that = this;
    console.log('监听到数据变化的值',readParameterVal)
    switch(this.data.readParameterID){
      case 24:
        this.setData({
          "PMSMbackEMFUpload":(readParameterVal/10).toFixed(1)
        })
        break;
      case 25:
        this.setData({
          "motorParameterSelfTestUpload":readParameterVal
        })
        break;
      case 26:
        this.setData({
          "motorControlMethodUpload":readParameterVal
        })
        break;
      case 27:
        this.setData({
          "ratedPowerUpload":(readParameterVal/10).toFixed(1)
        })
        break;
      case 28:
        this.setData({
          "ratedVoltageUpload":readParameterVal
        })
        break;
      case 29:
        this.setData({
          "ratedCurrentUpload":(readParameterVal/100).toFixed(2)
        })
        break;
      case 30:
        this.setData({
          "ratedSpeedUpload":readParameterVal
        })
        break;
      case 31:
        this.setData({
          "ratedFrequencyUpload":(readParameterVal/10).toFixed(1)
        })
        break;
      default:
        console.log("未找到对应ID值");
    }
    console.log(this.data.PMSMbackEMFUpload);

  },
   
  

  send (id,value) {
    if(!app.globalData.writePermission){
      wx.showToast({
        title: '您没有修改权限',
        icon: 'none',
        duration: 2000
      })
      return
    }
    let self = this
    let pk = self.data.pk
    let dk = self.data.dk
    let type = 'WRITE-ATTR'  
    let twosComplement = (~-parseInt(value) + 1) & 0xFFFF;
    let str = self.data.destinationStationAddress + self.data.functionCode["PresetSingleRegister"] + self.data.modBusIdtoAdd[id] + CRC.zeroPad(parseInt(twosComplement).toString(16),4)
    let modbusCode = str + CRC.ToModbusCRC16(str)
    console.log("发送请求的modbusCode:"+modbusCode);
    let sendData = [{
      id: 1,
      value: modbusCode.toUpperCase(),
      type: "RAW"
    }]
    app.globalData.mySocket.sendCmd({ pk, dk, type, sendData })
  },
  readParam (id) {
    let self = this
    let pk = self.data.pk
    let dk = self.data.dk
    let type = 'WRITE-ATTR'  
    let str = self.data.destinationStationAddress + self.data.functionCode["ReadHoldingRegister"] + self.data.modBusIdtoAdd[id] + "0001"
    let modbusCode = str + CRC.ToModbusCRC16(str)
    console.log("发送请求的modbusCode(读取):"+modbusCode);
    let sendData = [{
      id: 1,
      value: modbusCode.toUpperCase(),
      type: "RAW"
    }]
    app.globalData.mySocket.sendCmd({ pk, dk, type, sendData })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    app.globalData.pageID = "0"
    console.log("退出当前页面,pageID:"+ app.globalData.pageID)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  /*减速时间-区间限制*/
  handleDecelerationTimeChange: function(e) {
    this.handleTextChange(e, 10, 0.1, 500.0);
  },  
  /*加速时间-区间限制*/
  handleAccelerationTimeChange: function(e) {
    this.handleTextChange(e, 10, 0.1, 500.0);
  },
  handleMaxFrequencyChange: function(e) {
    this.handleTextChange(e, 10, 0.0, 599.9);
  },
  handleScheduledRunningTimeChange: function(e) {
    this.handleTextChange(e, 10, 0.0, 6500.0);
  },
  handleUserPasswordChange: function(e) {
    this.handleTextChange(e, 1, 0, 65535);
  },
  handleAccumulatedPpowerOnTimeChange: function(e) {
    this.handleTextChange(e, 1, 0, 17520);
  },
  handlePMSMbackEMFChange: function(e) {
    this.handleTextChange(e, 10, 0.0, 6553.5);
  },
  handleRatedPowerChange: function(e) {
    this.handleTextChange(e, 10, 0.1, 1000.0);
  },
  handleRatedVoltageChange: function(e) {
    this.handleTextChange(e, 1, 1, 500);
  },
  handleRatedCurrentChange: function(e) {
    this.handleTextChange(e, 100, 0.01, 655.35);
  },
  handleRatedSpeedChange: function(e) {
    this.handleTextChange(e, 1, 1, 65535);
  },
  handleRatedFrequencyChange: function(e) {
    this.handleTextChange(e, 10, 0.0, 599.9);
  },
  handleTorqueSetValueChange: function(e) {
    this.handleTextChange(e, 10, -200.0, 200.0);
  },
  handleHighSpeedVelocityGainChange: function(e) {
    this.handleTextChange(e, 1, 0, 100);
  },
  handleMKIChange: function(e) {
    this.handleTextChange(e, 1, 0, 30000);
  },
  handleMKPChange: function(e) {
    this.handleTextChange(e, 1, 0, 30000);
  },
  /*输入框信息校验*/
  handleTextChange:function(e, calculationParameters, lowLimit, highLimit) {
    let value = e.detail.value;
    if(value === ''){
      this.setData({
        [e.currentTarget.dataset.action + 'Judge']: false,
        [e.currentTarget.dataset.action + 'Uploaded']: false,
      });
      return;
    }
    if(value >= lowLimit && value <= highLimit){
      this.setData({
        [e.currentTarget.dataset.action + "Display"]: value,
        [e.currentTarget.dataset.action + "Upload"]: value * calculationParameters,
        [e.currentTarget.dataset.action + "Judge"]:true,
        [e.currentTarget.dataset.action + 'Uploaded']: false,
      });
      console.log("Id:" + this.data[e.currentTarget.dataset.action + "Id"] + " 显示值:" + this.data[e.currentTarget.dataset.action + "Display"] + " 上传值:" + this.data[e.currentTarget.dataset.action + "Upload"]);
    }else{
      wx.showToast({
        title: '输入超限',
        icon: 'error',
        duration: 2000
      });
      this.setData({
        [e.currentTarget.dataset.action + 'Display']:'',
        [e.currentTarget.dataset.action + 'Upload']:'',
        [e.currentTarget.dataset.action + 'Judge']: false,
        [e.currentTarget.dataset.action + 'Uploaded']: false,
      });
    }
  },
  /*信息上传*/
  handleValueUpload: function(e){
    let id = this.data[e.currentTarget.dataset.action + 'Id'];
    let value = this.data[e.currentTarget.dataset.action + 'Upload'];
    this.setData({
      [e.currentTarget.dataset.action + 'Uploaded'] : true,
    });
    if(value != ""){
      this.send(id , value);
    }
    console.log("Id:" + id + " 上传值:" + value);
  },
  /*筛选框信息上传*/
  handleSelectorChange: function(e) {
    let variable = e.currentTarget.dataset.action;
    let id = variable + "Id";
    let value = variable + "Upload";
    let judge = variable + "Uploaded";
    this.setData({
      [value]: e.detail.value,
      [judge]: true
    })
    this.send(this.data[id] , this.data[value]);
    console.log("Id:" + this.data[id] + " Value:" + this.data[value] );
  },
  handleGetBack: function() {
    wx.navigateTo({
      url: `/pages/device_detail/CommonDetail/index?item=${JSON.stringify(this.data.curDevice)}`,
    })
  },
  rePwd(){//应用权限更改
    let self = this
    let writeCorrectPassword = app.globalData.writePassword
    let readCorrectPassword = app.globalData.readPassword
    wx.showModal({
      title: '请输入权限密码',
      content: '',
      editable: true,
      success (res) {
        if (res.confirm) {  
          if (res.content === readCorrectPassword) {
            try {
              wx.setStorageSync('Pwd', readCorrectPassword);
              // wx.reLaunch({
              //   url: '/pages/home/home',
              // }) 
              // 设置成功
            } catch (err) {
              // 设置失败
              console.error(err);
            }
            wx.showToast({
              title: '密码正确(只读)',
              icon: 'none',
              duration: 1000
            })
            app.globalData.isAuthorized = true
            app.globalData.writePermission = false 
          } else if (res.content === writeCorrectPassword){
            try {
              wx.setStorageSync('Pwd', writeCorrectPassword);
              // wx.reLaunch({
              //   url: '/pages/home/home',
              // }) 
              // 设置成功
            } catch (err) {
              // 设置失败
              console.error(err);
            }
            wx.showToast({
              title: '密码正确(允许读写)',
              icon: 'none',
              duration: 1000
            })
            // app.globalData.writePermission = true
            app.globalData.isAuthorized = true
            app.globalData.writePermission = true 
          }else {
            // 密码错误，弹出提示框
            wx.showToast({
              title: '密码错误',
              icon: 'none',
              duration: 2000
            })
          }
        } else if (res.cancel) {
        }
      }
    }) 
      
    
  },
  
  readParamBtn(e){
    let id = this.data[e.currentTarget.dataset.action + 'Id'];
    let value = this.data[e.currentTarget.dataset.action + 'Upload'];
    this.setData({
      readParameterID:id
    })
    console.log("btn设置id为：" + this.data[e.currentTarget.dataset.action + 'Id']);
    this.readParam(id)
    // app.globalData.readParameterVal += 1
  }
})

